<template>
	<div class="tem-and-hum-container">
		<el-row class="header-box">
			<el-col :span="8" class="header-box-left">
				<kan-ban-dropdown
					v-model="searchParams.workshopId"
					:option-list="workshopList"
					size="mini"
					class="item-gap"
					@change="onSelectDropdown"
				></kan-ban-dropdown>
				<el-radio-group v-model="comName" size="mini">
					<el-tooltip class="item" effect="dark" content="列表布局">
						<el-radio-button label="listView">
							<span class="el-icon-s-grid"></span>
						</el-radio-button>
					</el-tooltip>
					<el-tooltip class="item" effect="dark" content="区域布局">
						<el-radio-button label="layoutView">
							<span class="el-icon-house"></span>
						</el-radio-button>
					</el-tooltip>
				</el-radio-group>
			</el-col>
			<el-col :span="8" class="header-box-title">区域设备及环境监控</el-col>
			<el-col :span="8" class="header-box-right">
				<span class="current-time">{{ currentTime }}</span>
				<jk-full-screen-button v-if="fromPage !== 'largeScreen'" class-name="tem-and-hum-container"></jk-full-screen-button>
				<el-button v-if="fromPage !== 'largeScreen'" :loading="refreshBtnLoading" size="mini" type="primary" icon="el-icon-refresh" style="margin-left: 4px;" @click="onRefreshBtn"></el-button>
			</el-col>
		</el-row>
		<div class="legend-box">
			<div class="legend-box-inner">
				<legend-box :machine-state-list="machineStateList"></legend-box>
				<!--<marquee style="color: #2d8cf0;width: 100%;" class="el-icon-">{{ errorMsgList && errorMsgList.length ? `⚠️ 警告：${errorMsgList.map(x => `${x.machineCode}(${x.specParamName})`).join('，')}异常, 请及时处理!` : '👏🧨欢迎使用，捷控物联智能纺纱MES系统!🧨👏' }}️</marquee>-->
			</div>
		</div>
		<article class="article-box">
			<div class="chart-item-inner">
				<div
					ref="scrollContainer"
					class="content-left-box"
				>
					<component
						:is="comName"
						:form-data="ruleForm"
						:process-list="processList"
						@click="onMachineItem"
					></component>
				</div>
				<div class="content-right-box">
					<div class="chart-container">
						<div style="height: 200px;">
							<div class="chart-title">机台状态分布</div>
							<machine-state-chart :chart-data="machineStateList"></machine-state-chart>
						</div>
						<!--<div style="height: 50%;">
							<div class="chart-title">工艺异常分布</div>
							<technology-item-pie :chart-data="itemLayoutData"></technology-item-pie>
						</div>-->
						<div style="height: calc(100% - 200px);">
							<div class="chart-title">区域温湿度监控</div>
							<floorTemHumChart style="height: calc(100% - 40px);" :refresh-data="rdVal" :span="24"></floorTemHumChart>
							<!--<el-row
								v-for="(item, index) in errorMsgList"
								:key="index"
								class="alert-msg-item"
								style="color: #ed4014;"
							>
								<el-col :span="9" class="alert-msg-status text-ellipsis">
									&lt;!&ndash;<span>{{ index + 1 }}.</span>&ndash;&gt;
									<div style="color: #ed4014;" class="alert-msg-status-icon el-icon-warning"></div>
									<span>{{ item.createTime | fTime }}</span>
								</el-col>
								<el-col :span="11" class="alert-msg-txt text-ellipsis">
									<span>{{ item.machineCode }} {{ item.specParamName }}</span>
								</el-col>
								<el-col :span="4" class="alert-msg-txt text-ellipsis" style="color: #2d8cf0;cursor: pointer;" @click.native="onHandlerMsgItem(item)">处理</el-col>
							</el-row>-->
						</div>
					</div>
				</div>
			</div>

		</article>
		<detail-dialog
			ref="detailDialog"
			:data-item="dataItem"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
	</div>
</template>
<script>
    import bottomChart from './components/bottom-chart';
    import { formatTime } from '../../../utils/jk/jk-tool';
    import kanBanDropdown from '../kanBan/componenst/kan-ban-dropdown';
    import detailDialog from './detail-dialog';
    import machineStateChart from './components/machine-state-chart';
    import technologyItemPie from './components/technology-item-layout-chart';
    import { machineManagerMachineGetAllRunState, workshopLayoutGetByWorkshopId } from '../../../api/intelligence';
    import colorMixin from '../orderTracking/colors-mixin';
    import listView from './components/view-type/list-view';
    import layoutView from './components/view-type/layout-view';
    import legendBox from './components/legend-box/index';
    import {
        productionMachineSpecMonitoringRecordPage,
        productionMachineSpecMonitoringRecordRead
    } from '../../../api/production/productionMonitor';
    import { machineManagerMachineGetHumiture } from '../../../api/production/kanBan';
    import floorTemHumChart from '../kanBan/componenst/charts/floor-tem-hum';
    import { mathJsAdd, mathJsSub } from '../../../utils/jk/jk-cals';
    export default {
        props: {
            fromPage: {
                type: String,
                default: ''
            },
            killTimer: {
                type: [Number, String],
                default: ''
            }
        },
        components: {
            floorTemHumChart,
            legendBox,
            layoutView,
            listView,
            technologyItemPie,
            machineStateChart,
            detailDialog,
            kanBanDropdown,
            bottomChart
        },
        mixins: [colorMixin],
        data() {
            return {
                comName: 'listView',
                errorMsgList: [],
                ruleForm: {
                    machineLayoutList: []
                },
                dataItem: {},
                detailDialogState: false,
                workshopList: [],
                searchParams: {
                    workshopId: null,
                    customerName: ''
                },
                refreshBtnLoading: false,
                currentTime: '',
                timer: {},
                timer2: {},
                processList: [],
                itemLayoutData: [],
                temAndHumData: [],
                rdVal: null,
                timer3: {}
            };
        },
        filters: {
            fTime(e) {
                const d = new Date(e);
                const month = d.getMonth() + 1 < 10 ? `0${d.getMonth() + 1}` : d.getMonth() + 1;
                const day = d.getDate() < 10 ? `0${d.getDate()}` : d.getDate();
                const h = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours();
                const m = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes();
                const s = d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds();
                return `${month}-${day} ${h}:${m}:${s}`;
            }
        },
        methods: {
            onHandlerMsgItem({ id }) {
                productionMachineSpecMonitoringRecordRead({ id }).then(res => {
                    if (res.data.status === 200) {
                        this.getMsgRequest();
                        this.getListRequest();
                    }
                });
            },
            onMachineItem(e) {
                const workshopItem = this.workshopList.find(x => x.id === this.searchParams.workshopId) || {};
                this.dataItem = {
                    ...e,
                    workshopId: workshopItem.id,
                    workshopCode: workshopItem.code,
                    workshopName: workshopItem.name
                };
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                this.detailDialogState = e;
            },
            onSelectDropdown(e) {
                this.refresh = Math.random();
                this.$set(this.searchParams, 'workshopId', e);
                (async() => {
                    await this.getListRequest();
                    await this.getWorkshopLayoutList();
                })();
            },
            onRefreshBtn() {
                this.runRequest();
            },
            getCurrentTime() {
                this.currentTime = formatTime(Date.now());
                this.timer = setInterval(() => {
                    this.currentTime = formatTime(Date.now());
                }, 1000);
            },
            getErrorItemLayout(arr) {
                const itemConfig = {};
                arr.forEach(processItem => {
                    processItem.machineRunStateList.forEach(machineItem => {
                        machineItem.machineSpecMonitoringList.forEach(item => {
                            if (!itemConfig[item.specParamName]) {
                                itemConfig[item.specParamName] = {
                                    name: item.specParamName,
                                    value: 1
                                };
                            } else {
                                itemConfig[item.specParamName].value++;
                            }
                        });
                    });
                });
                this.itemLayoutData = Object.values(itemConfig);
            },
            getListRequest() {
                this.refreshBtnLoading = true;
                if (!this.searchParams.workshopId) return;
                let arr = [];
                if (this.searchParams.workshopId === -1) {
                    arr = [];
                } else {
                    arr = [this.searchParams.workshopId];
                }
                return machineManagerMachineGetAllRunState({
                    workshopIds: arr,
                    processCode: ''
                }).then(res => {
                    this.refreshBtnLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res || [];
                        this.processList = resData;
                        // 初始化
                        this.machineStateList.forEach(legendItem => {
                            this.$set(legendItem, 'count', 0);
                        });
                        resData.forEach(processItem => {
                            processItem.machineRunStateList.forEach(machineItem => {
                                if (this.machineStateList.find(x => x.id === machineItem.state)) {
                                    this.machineStateList.forEach(legendItem => {
                                        if (legendItem.id === machineItem.state) {
                                            this.$set(legendItem, 'count', legendItem.count + 1);
                                        }
                                    });
                                }
                            });
                        });
                        this.getErrorItemLayout(resData);
                        this.ruleForm.machineLayoutList.forEach(layoutMachineItem => {
                            resData.forEach(processItem => {
                                processItem.machineRunStateList.forEach(machineItem => {
                                    if (layoutMachineItem.machineId === machineItem.machineId) {
                                        this.$set(layoutMachineItem, 'state', machineItem.state);
                                    }
                                });
                            });
                        });
                        this.runScroll();
                    }
                });
            },
            getWorkshopLayoutList() {
                if (this.searchParams.workshopId) {
                    return workshopLayoutGetByWorkshopId({ id: this.searchParams.workshopId }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                            resData.machineLayoutList = resData.machineLayoutList || [];
                            resData.machineLayoutList.forEach(machineItem => {
                                machineItem.styleConfig = machineItem.styleConfig ? JSON.parse(machineItem.styleConfig) : {};
                            });
                            this.ruleForm = resData;
                        }
                    });
                }
            },
            getTemAndHumRequest() {
                return machineManagerMachineGetHumiture({ typeCode: 'TEM_HUM' }).then(res => {
                    if (res.data.status === 200) {
                        this.temAndHumData = res.data.res || [];
                        this.ruleForm.machineLayoutList.forEach(machineItem => {
                            // 赋值温湿度
                            this.temAndHumData.forEach(thItem => {
                                if (thItem.machineCode === machineItem.machineCode) {
                                    this.$set(machineItem, 'temperature', thItem.temperature ? Number(thItem.temperature) : 0);
                                    this.$set(machineItem, 'humidity', thItem.humidity ? Number(thItem.humidity) : 0);
                                    this.$set(machineItem, 'temState', thItem.temState);
                                    this.$set(machineItem, 'humState', thItem.humState);
                                }
                            });
                        });
                    }
                });
            },
            getMsgRequest() {
                return productionMachineSpecMonitoringRecordPage({
                    workshopId: this.searchParams.workshopId,
                    selectSpecMonitoring: true,
                    ifHandler: false
                }).then(res => {
                    if (res.data.status === 200) {
                        this.errorMsgList = res.data.res ? res.data.res : [];
                    }
                });
            },
            async getDependentData() {
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', -1);
                    // this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                this.workshopList = [
                    { id: -1, name: '全部' },
                    ...this.$store.state.user.userWorkshop.workshopList
                ];
                await this.getMsgRequest();
                await this.getListRequest();
                await this.getWorkshopLayoutList();
                await this.getTemAndHumRequest();
                this.run();
            },
            clearTime() {
                clearInterval(this.timer);
                clearInterval(this.timer2);
                clearInterval(this.timer3);
            },
            runRequest() {
                this.getTemAndHumRequest();
                this.getMsgRequest();
                this.getListRequest();
            },
            scrollTo(e) {
                this.$refs.scrollContainer.scrollTop = e;
            },
            runScroll() {
                clearInterval(this.timer3);
                this.timer3 = setInterval(() => {
                    if (this.$refs.scrollContainer) {
                        if (this.$refs.scrollContainer.scrollHeight > this.$refs.scrollContainer.clientHeight) {
                            const scrollContainer = this.$refs.scrollContainer;
                            if (scrollContainer) {
                                if (Math.floor(mathJsSub(this.$refs.scrollContainer.scrollHeight, this.$refs.scrollContainer.scrollTop)) > scrollContainer.clientHeight) {
                                    this.$refs.scrollContainer.scrollTop = mathJsAdd(this.$refs.scrollContainer.scrollTop, 1);
                                } else {
                                    this.$refs.scrollContainer.scrollTop = 0;
                                }
                            }
                        }
                    }
                }, 60);
            },
            run() {
                this.getListRequest();
                this.rdVal = Math.random();
                clearInterval(this.timer2);
                this.timer2 = setInterval(() => {
                    this.rdVal = Math.random();
                    this.runRequest();
                }, 1000 * 2);
            }
        },
        mounted() {
            this.getDependentData();
        },
        destroyed() {
            this.clearTime();
        },
        watch: {
            killTimer() {
                this.clearTime();
            }
        },
        beforeRouteEnter(to, from, next) {
            next((_this) => {
                _this.getCurrentTime();
                _this.getDependentData();
            });
        },
        beforeRouteLeave(to, from, next) {
            this.clearTime();
            this.$nextTick(() => {
                this.$refs.detailDialog.clearTimer();
            });
            next();
        }
    };
</script>
<style scoped lang="scss">
    @import "index";
</style>
